<template>
  <el-container>
    <el-header>
      <el-button @click="$router.push('/')">返回首页</el-button>
    </el-header>
    <el-main>
      <el-row justify="center">
        <el-col :span="8">
          <el-card>
            <h2>后台登录</h2>
            <el-form
              :model="form"
              :rules="rules"
              ref="loginForm"
              label-width="80px"
            >
              <el-form-item label="用户名" prop="username">
                <el-input v-model="form.username" />
              </el-form-item>
              <el-form-item label="密码" prop="password">
                <el-input v-model="form.password" type="password" />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="onLogin">登录</el-button>
              </el-form-item>
            </el-form>
          </el-card>
        </el-col>
      </el-row>
    </el-main>
  </el-container>
</template>

<script setup>
import { ref } from 'vue'
import api from '../api'
import { useRouter } from 'vue-router'

const router = useRouter()
const form = ref({ username: '', password: '' })
const rules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
}

const onLogin = async () => {
  try {
    const res = await api.post('/login', form.value)
    localStorage.setItem('token', res.data.token)
    router.push('/')
  } catch (e) {
    alert('登录失败')
  }
}
</script>
